package com.spring.boot.demo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @Date: 2022/10/31 23:03
 * @Description 自定义拦截器处理 cors 跨域问题
 */
public class CorsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Cors跨域拦截器【preHandle】......");
        // 设置 cors跨域访问的 响应头
        // 允许浏览器携带Cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许访问的域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许访问的请求方式
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        // OPTIONS 请求的缓存时间
        response.setHeader("Access-Control-Max-Age", "3600");
        // 获取请求方式,如果是 OPTIONS 请求, 则直接返回,拦截器不执行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            // 直接响应成功即可, OPTIONS 请求的目的就是为了判断是否服务器允许跨域访问
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Cors跨域拦截器【postHandle】......");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Cors跨域拦截器【afterCompletion】......");
    }
}
